﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.OleDb;
using System.Data;
using System.Text;

namespace LongSpeed.WebSite.Behaviors
{
    public class Part
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public bool IsSys { get; set; }
        public int SortIndex { get; set; }
        public string Memo { get; set; }
        /// <summary>
        /// 映射请求地址
        /// </summary>
        public string FromUrl { get; set; }
        /// <summary>
        /// 映射Id
        /// </summary>
        public string UrlMappingId { get; set; }

        public PartViewType ViewType { get; set; }

        /// <summary>
        /// 获取栏目
        /// </summary>
        /// <param name="isOnlyGetShowInMemu">是否只获取显示到菜单的栏目
        /// <para>1、false 获取所有</para>
        /// <para>2、true 获取显示到菜单的栏目</para>
        /// </param>
        /// <returns></returns>
        public IList<Part> GetPart(bool isOnlyGetShowInMemu = false)
        {
            IList<Part> parts = new List<Part>();

            string cmdStr = " SELECT   *  FROM      T_Part ";

            if (isOnlyGetShowInMemu)
            {
                cmdStr += " where IsSys = true ";
            }

            var ds = OleDbHelper.Query(cmdStr);

            if (ds.Tables.Count > 0)
            {
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    Part m = RowToEntity(row);
                    parts.Add(m);
                }
            }

            return parts;
        }
        private static Part RowToEntity(DataRow row)
        {
            Part m = new Part()
            {
                ID = Convert.ToInt32(row["ID"]),
                Memo = row["Memo"] + "",
                Name = row["P_Name"] + "",
                SortIndex = Convert.ToInt32(row["SortIndex"]),
                IsSys = Convert.ToBoolean(row["IsSys"]),
                ViewType = (PartViewType)Convert.ToInt32(row["ViewType"]),
                FromUrl = row["FromUrl"] + "",
                UrlMappingId = row["UrlMappingId"] +""//== DBNull.Value ? 0 : Convert.ToInt32(row["UrlMappingId"])
            };
            return m;
        }
        public void Init(int id)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append(" SELECT  *  FROM      T_Part  where ID=" + id);
            var ds = OleDbHelper.Query(strSql.ToString());

            if (ds.Tables.Count > 0)
            {
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    var p = RowToEntity(row);
                    this.ID = p.ID;
                    this.Memo = p.Memo;
                    this.Name = p.Name;
                    this.SortIndex = p.SortIndex;
                    this.IsSys = p.IsSys;
                    this.ViewType = p.ViewType;
                    this.FromUrl = p.FromUrl;
                    this.UrlMappingId = p.UrlMappingId;
                    break;
                }
            }
        }
        public bool Save()
        {
            object name, memo, fromurl;
            if (this.Name == null) name = DBNull.Value; else name = this.Name;
            if (this.Memo == null) memo = DBNull.Value; else memo = this.Memo;
            if (this.FromUrl == null) fromurl = DBNull.Value; else fromurl = this.FromUrl;

            UrlMapping urlMapping = new UrlMapping()
            {
                FormAddress = this.FromUrl,
                ID = this.UrlMappingId == "" ? 0 : Convert.ToInt32(this.UrlMappingId)
            };

            switch (this.ViewType)
            {
                case PartViewType.List:
                    urlMapping.Args = string.Format("apart={0}", this.ID);
                    urlMapping.ToAddress = "~/Main/ArticleListView.aspx";
                    break;
                case PartViewType.Info:
                    urlMapping.Args = string.Format("aid={0}&apart={1}", 0, this.ID);
                    urlMapping.ToAddress = "~/Main/ArticleInfo.aspx";
                    break;
            }

            string execSql = "";
            if (this.ID == 0)
            {
                urlMapping.Add(urlMapping);
                this.UrlMappingId = urlMapping.ID+"";

                execSql = @" insert into   T_Part ( P_Name, IsSys, SortIndex, [Memo],ViewType,FromUrl,UrlMappingId  ) values
                                                                   ( @P_Name, @IsSys, @SortIndex,  @Memo ,@ViewType,@FromUrl,@UrlMappingId) ";
                System.Data.OleDb.OleDbParameter[] par = new System.Data.OleDb.OleDbParameter[] {
                    new System.Data.OleDb.OleDbParameter("@P_Name",name),
                    new System.Data.OleDb.OleDbParameter("@IsSys",this.IsSys),
                    new System.Data.OleDb.OleDbParameter("@SortIndex",this.SortIndex),
                    new System.Data.OleDb.OleDbParameter("@Memo",memo),
                    new System.Data.OleDb.OleDbParameter("@ViewType", Convert.ToInt32( this.ViewType)),
                    new System.Data.OleDb.OleDbParameter("@FromUrl" ,fromurl),
                    new System.Data.OleDb.OleDbParameter("@UrlMappingId" ,this.UrlMappingId)
                };

                if (OleDbHelper.ExecuteSql(execSql, par) > 0)
                {
                    this.ID = OleDbHelper.GetMaxID("ID", "T_Part");
                    return true;
                }
            }
            else
            {
                urlMapping.Update(urlMapping);
                this.UrlMappingId = urlMapping.ID+"";

                execSql = @"update   T_Part  set P_Name = @P_Name , IsSys = @IsSys, SortIndex = @SortIndex, 
                                [Memo]  =  @Memo ,ViewType=@ViewType,FromUrl=@FromUrl,UrlMappingId=@UrlMappingId  where ID = @ID";
                System.Data.OleDb.OleDbParameter[] par = new System.Data.OleDb.OleDbParameter[] {
                    new System.Data.OleDb.OleDbParameter("@P_Name",name),
                    new System.Data.OleDb.OleDbParameter("@IsSys",this.IsSys),
                    new System.Data.OleDb.OleDbParameter("@SortIndex",this.SortIndex),
                    new System.Data.OleDb.OleDbParameter("@Memo",memo),
                    new System.Data.OleDb.OleDbParameter("@ViewType", Convert.ToInt32( this.ViewType)),
                    new System.Data.OleDb.OleDbParameter("@FromUrl" ,fromurl),
                    new System.Data.OleDb.OleDbParameter("@UrlMappingId" ,this.UrlMappingId),
                    new System.Data.OleDb.OleDbParameter("@ID", this.ID),
                };

                if (OleDbHelper.ExecuteSql(execSql, par) > 0)
                {
                    return true;
                }
            }

            return false;
        }
        public bool Delete()
        {
            bool result = false;
            string execSql = "";
            execSql = "delete from T_Part where  ID = @ID ";
            System.Data.OleDb.OleDbParameter par = new System.Data.OleDb.OleDbParameter("@ID", OleDbType.Integer) { Value = this.ID };

            string delArticle = " delete from T_ServerConfig where MemuId = @ID";

            OleDbConnection conn = new OleDbConnection(System.Configuration.ConfigurationManager.ConnectionStrings["OleDbConnStr"].ConnectionString);
            conn.Open();

            //   开启事务   
            OleDbTransaction oledbTransaction = conn.BeginTransaction();
            try
            {
                UrlMapping urlmapping = new UrlMapping();

                if (string.IsNullOrEmpty(this.FromUrl) || urlmapping.Delete(this.FromUrl))
                {
                    //   将事务应用于Command   
                    OleDbCommand oledbCommand = new OleDbCommand();
                    oledbCommand.Connection = conn;
                    oledbCommand.Transaction = oledbTransaction;
                    oledbCommand.Parameters.Add(par);

                    oledbCommand.CommandText = delArticle;
                    oledbCommand.ExecuteNonQuery();

                    oledbCommand.CommandText = execSql;
                    oledbCommand.ExecuteNonQuery();


                    oledbTransaction.Commit();
                    result = true;
                }
                else
                {
                    result = false;
                }
            }
            catch (Exception)
            {
                oledbTransaction.Rollback();
                //CommonLib.Session.SaveLog(ex);
                result = false;
            }
            finally
            {
                conn.Close();
            }

            return result;
        }
    }
    public enum PartViewType
    {
        /// <summary>
        /// 展示改栏目下的所有文章列表
        /// </summary>
        List = 0,
        /// <summary>
        /// 展示该栏目下的第一篇文章的完全信息
        /// </summary>
        Info = 1,
    }
}